package top.huntwolf.admin.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.dao.ExhibitionDao;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.pojo.Exhibition;
import top.huntwolf.admin.pojo.Subject;
import top.huntwolf.admin.pojo.book.BuyBook;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ExhibitionService {

    @Autowired
    ExhibitionDao exhibitionDao;

    //返回所有栏目表信息
    public List<Exhibition> searchAllExhibition(){
        return exhibitionDao.selectAll();
    }
    //根据id返回 （栏目表 + 书本list）信息
    public Exhibition searchExhibitionById(String exhibitId){
        return exhibitionDao.selectById(exhibitId);
    }

    //更新栏目信息
    public void updateSearchExhibition(Exhibition exhibition){

        //- 1、更新 exhibition 数据
        exhibitionDao.updateExhibitionInfo(exhibition);

        //- 2、获得书本 <isbn> list
        List<BuyBook> booklist = exhibition.getBooklist();

        //  - 2.1 删除栏目已有的数据
        exhibitionDao.delete(exhibition.getExhibitId());


        //  - 2.2 增加exhibition_book表数据
        if(booklist.size() != 0){
            for (BuyBook buyBook : booklist) {
                Map<String,Object> map = new HashMap<>();
//                System.out.println(exhibition.getExhibitId()+" --"+buyBook.getIsbn());
                map.put("exhibitId",exhibition.getExhibitId());
                map.put("isbn",buyBook.getIsbn());
                exhibitionDao.Insert(map);
            }
        }

    }

    public void insertExhibition(Exhibition exhibition){
        exhibitionDao.InsertExhibition(exhibition);
    }

    public List<BuyBook> searchBookInfo(String id,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<BuyBook> bookList = exhibitionDao.selectBookInfo(id);
        PageInfo pageInfo = new PageInfo(bookList);

        if (pageNum > pageInfo.getPages()){
            throw new ServiceException(CodeMsg.MAX_PAGES.fillArgs("没有更多内容"));
        }
        return bookList;
    }



}
